package com.xiaojie.service.impl;


import com.alibaba.fastjson2.JSONObject;
import com.xiaojie.entity.Order;
import com.xiaojie.mapper.OrderMapper;
import com.xiaojie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * @author xiaojie
 * @version 1.0
 * @description:
 * @date 2021/10/11 22:09
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService, RabbitTemplate.ConfirmCallback {
    //定义交换机
    private static final String XIAOJIE_ORDER_EXCHANGE = "xiaojie_order_exchange";
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    @Transactional
    public String saveOrder() {
        Order order = new Order();
        String orderId = UUID.randomUUID().toString();
        order.setOrderId(orderId);
        order.setOrderName("小谷姐姐麻辣烫");
        order.setPayMoney(35.68);
        order.setStatus(1);//假设订单支付完成
        int result = orderMapper.addOrder(order);
        if (result < 0) {
            return "下单失败";
        }
        //发送派单
        String orderJson = JSONObject.toJSONString(order);
        sendDispatchMsg(orderJson);
        //模拟报错
        int i = 1 / 0;
        return orderId;
    }

    @Async
    public void sendDispatchMsg(String jsonMSg) {
        // 设置生产者消息确认机制
        this.rabbitTemplate.setMandatory(true);
        this.rabbitTemplate.setConfirmCallback(this);
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(jsonMSg);
        //将订单数据发送
        rabbitTemplate.convertAndSend(XIAOJIE_ORDER_EXCHANGE, "", jsonMSg, correlationData);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String s) {
        if (ack) {
            log.info(">>>>>>>>消息发送成功:correlationData:{},ack:{},s:{}", correlationData, ack, s);
        } else {
            log.info(">>>>>>>消息发送失败{}", ack);
        }
    }
}
